package com.jdk.thread.jstudy;

import org.junit.Test;

import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created with IntelliJ IDEA.
 * User: sjx
 * Date: 14-7-18
 * Time: 下午1:23
 * To change this template use File | Settings | File Templates.
 */
public class TestSemaphore {

    @Test
    public void test() throws InterruptedException {
        ExecutorService executorService = Executors.newCachedThreadPool();
        final SemaphorePool semaphorePool = new SemaphorePool(5);
        for (int i = 0; i < 500; i++) {
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    String string = semaphorePool.get();
                    try {
                        Thread.sleep(new Random().nextInt(5) * 1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
                    } finally {
                        semaphorePool.add(string);
                    }
                }
            });
        }
        Thread.sleep(Integer.MAX_VALUE);
    }

}
